﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace nwrole.plugin
{
    public class PluginBase : IPlugin
    {
        protected IPlugin Plugin { get; set; }

        //protected Solution.Instance Instance { get; set; }
        //protected Solution.Service Service { get; set; }
        //protected Solution Solution { get; set; }

        protected Thread Thread { get; set; }
        protected TimeSpan DelayStart { get; set; }
        protected List<PluginError> Errors = new List<PluginError>();
        protected bool Running { get; private set; }

        protected IPluginDebug debug;

        private AutoResetEvent waitEvent = new AutoResetEvent(false);

        public PluginBase() { }

        public void Initialize()
        {
            // Plugin = plugin;
            // Instance = instance;
            // Service = service;
            // Solution = solution;
            DelayStart = TimeSpan.FromSeconds(0);

            this.OnInit();
        }

        public void Start(IPluginDebug debug)
        {
            if (Thread != null && Thread.IsAlive)
                return;

            this.debug = debug;

            Running = true;
            Thread = new Thread(new ThreadStart(this.CoreStart));
            Thread.Start();

            waitEvent.WaitOne();
        }

        protected virtual void CoreStart()
        {
            Thread.Sleep(DelayStart);
            this.OnStart();
            this.Execute();
        }

        public void Stop()
        {
            waitEvent.Set();

            Running = false;

            if (Thread == null || !Thread.IsAlive)
                return;
            
            Thread.Join(TimeSpan.FromSeconds(10));
            Thread = null;

            this.CoreStop();
        }

        protected virtual void CoreStop()
        {
            this.OnStop();
        }

        protected virtual void OnInit() { }
        protected virtual void OnStart() { }
        protected virtual void OnStop() { }
        protected virtual void Execute() { }

        protected void RegisterError(string origin, string message)
        {
            Errors.Add(new PluginError(origin, message));
        }

        protected void RegisterError(string origin, string message, Exception exception)
        {
            Errors.Add(new PluginError(origin, message, exception));
        }

        public void ConfigurationChanged()
        {
        }

        //public event EventHandler<PluginLogEventArgs> LogEvent;

    }
}



//public void Initialize(Plugin plugin, Solution.Instance instance, Solution.Service service, Solution solution)
//{
//    Plugin = plugin;
//    Instance = instance;
//    Service = service;
//    Solution = solution;
//    DelayStart = TimeSpan.FromSeconds(0);

//    this.OnInit();
//}
